package com.gmrz.uaf.policy.json;

import java.lang.reflect.Type;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.google.gson.InstanceCreator;
import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParseException;
import com.google.gson.JsonSerializationContext;
import com.google.gson.JsonSerializer;
import com.gmrz.uaf.protocol.v1.schema.Policy;

public  class JSONAdapter implements InstanceCreator<JSONPolicyStore>,
		JsonSerializer<JSONPolicyStore>, JsonDeserializer<JSONPolicyStore> {
	private static final Logger LOG = LogManager
			.getLogger(JSONAdapter.class);

	public JSONPolicyStore createInstance(Type type) {
		return new JSONPolicyStore();
	}

	public JsonElement serialize(JSONPolicyStore src, Type typeofSrc,
			JsonSerializationContext context) {
		JsonObject retval = new JsonObject();
		for (Map.Entry e : src.getAllPolicies().entrySet()) {
			retval.add((String) e.getKey(), context.serialize(e.getValue()));
		}
		return retval;
	}

	public JSONPolicyStore deserialize(JsonElement json, Type typeofT,
			JsonDeserializationContext context) throws JsonParseException {
		JSONPolicyStore retval = new JSONPolicyStore();
		JsonObject object = json.getAsJsonObject();
		for (Map.Entry e : object.entrySet()) {
			Policy p = context.deserialize((JsonElement) e.getValue(),
					Policy.class);
			if (p == null) {
				LOG.error("Failed to deserialize null policy");
				throw new JsonParseException("Policy object is null");
			}
			p.setPolicyName((String) e.getKey());
			retval.getAllPolicies().put((String) e.getKey(), p);
		}

		return retval;
	}
}